var util = require('../../utils/util.js');
var app = getApp()
Page({
  data: {
    shopLogo: '',
    today: '',
    imgurl: '',
    bookArr: [],
    st: 0,
    sendTypeArr: ["快递发货", "同城配送", "门店自提"],
    sendType: 'all', // 配送方式
    mdType: 0, // 门店
    mdTypeArr: [],
    mdName: '',
    mdIds: [],
    mdId: 0,
    ztTime: '09:00', // 自提时间
    ztStart: '00:01',
    ztEnd: '23:59',
    tcTime: '09:00', // tc时间
    allTimeArr: [],
    week: '', // 营业周期
    weekArr: [],
    couponsNum: 0,//优惠券数量
    couponsParam: '',//查询参数
    coupon: {},
    couponInfo: '',
    goodTotalPrice: 0,
    finalPrice: 0,
    discountPrice: 0,
    date: "年/月/日",
    sendPrice: 0,
    message: '',
    shop: {},
    goodsList: [],
    mdList: [],
    express: {},
    sendName: '',
    sendPhone: '',
    sendAddress: ''
  },
  onLoad: function (options) {
    var that = this
    var shopInfo =  app.shopInfo
    if (shopInfo){
      that.setData({ shopLogo: shopInfo.shopLogo })
    }
    that.setData({ imgurl: app.imageUrl })
    util.setColor(that);//配色
    // 获得今天日期
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const today = year + '-' + (parseInt(month) <= 9 ? '0' + month : month) +'-'+ (parseInt(day) <= 9 ? '0' + day : day)
    that.setData({today: today })
    // 接收传递参数
    var urlStr = options.bookArr
    // urlStr = unescape(urlStr);
    var bookArr = JSON.parse(urlStr)
    var ty = options.ty
    var gno = options.gno
    // 总价
    var tp = 0
    for(var i = 0; i < bookArr.length; i++){
      var garr = bookArr[i].ggArr // 规格
      for(var j = 0; j < garr.length; j++){
        tp += parseInt(garr[j].buyNum) * parseFloat((ty == 'pp_pt' || ty == 'pp_ct') ? garr[j].obj.groupPrice : garr[j].obj.price)
      }
    }
    that.setData({ bookArr: bookArr, finalPrice: tp.toFixed(2), goodTotalPrice: tp.toFixed(2), ty: ty, gno: gno })
    that.getBookArrInfo()
    that.getCouponsNum()
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
    var that = this
    that.setData({ showNoneRefresh: false })
    // 优惠券使用
    var coupon = wx.getStorageSync("couponObj")
    var isUse = wx.getStorageSync("isUseCoupon")
    if (isUse == 'unuse'){//未使用
      //计算优惠价格
      var pri = 0
      var toPri = parseFloat(that.data.goodTotalPrice)//未优惠产品总价
      var yfPri = parseFloat(that.data.sendPrice)
      if (coupon.discountType == 'price') {
        pri = parseFloat(coupon.discountValue)
      } else {
        if (coupon.useGoodsType == 'all') {//all
          pri = (parseFloat(toPri) * parseFloat((10 - parseFloat(coupon.discountValue)) / 10)).toFixed(2)
        } else {//指定id
          var needPri = that.findByGoodId(coupon.goodsId)
          pri = (parseFloat(needPri) * parseFloat((10 - parseFloat(coupon.discountValue)) / 10)).toFixed(2)
        }
      }

      var info = '已选' + coupon.couponName
      that.setData({ coupon: coupon, finalPrice: (toPri - pri + yfPri).toFixed(2), discountPrice: pri.toFixed(2), couponInfo: info })
      wx.removeStorageSync("isUseCoupon")
      wx.removeStorageSync("couponObj")
    }
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  bindSendType(e) {// 设置配送类型
    var that = this
    var i = e.detail.value
    var sendType = that.data.sendType
    that.setData({ st: i })
    if(sendType == 'all'){
      var goodTotal = parseFloat(that.data.goodTotalPrice)
      var discount = parseFloat(that.data.discountPrice)
      var sendPrice = parseFloat(that.data.sendPrice)
      if (parseInt(i) != 2) {// 快递&&同城
        that.setData({ mdId: 0, mdName: '', finalPrice: (goodTotal - discount + sendPrice).toFixed(2) })
      }else{
        that.setData({ finalPrice: (goodTotal - discount).toFixed(2) })
      }
    } else if (sendType != 'md'){
      that.setData({ mdId: 0, mdName: '' })
    }
    
  },
  bindchooseaddress: function () {
    var that = this
    wx.chooseAddress({
      success: function (res) {
        var dz = res.provinceName + res.cityName + res.countyName + ' ' + res.detailInfo
          + ' ' + res.postalCode
        that.setData({ sendName: res.userName, sendPhone: res.telNumber, sendAddress: dz })
      }
    })
  },
  bindDateChange: function (e) {
    var date = e.detail.value
    if (parseInt(this.data.sendType) == 2){//门店,过滤营业周期
     var week = this.data.week// 门店的周期
     week = this.optionWeeks(week)
     var dr = date.split('-')
     var time = new Date(dr[0], parseInt(dr[1] - 1), dr[2])
     var we = time.getDay()// 所选日期为周几
     if(week.indexOf(we) < 0){
       wx.showModal({ title: '提示', content: '自提门店当天不营业，请重新选择！', showCancel: false })
       return
     }
    }
    this.setData({ date: date })
  },
  bindMdType(e) {// 门店自提设置
    var that = this
    var i = e.detail.value
    var arr = []// 设置门店时间
    var tt = that.data.allTimeArr[i]
    arr = tt.split('-')
    var wearr = that.data.weekArr//设置营业周期
    var idArr = that.data.mdIds
    var nameArr = that.data.mdTypeArr
    that.setData({ mdType: e.detail.value, ztStart: arr[0], ztEnd: arr[1], week: wearr[i], mdId: idArr[i], mdName: nameArr[i] })
  },
  bindInputMsg(e) {
    this.setData({ message: e.detail.value })
  },
  toDetail: function () {
    wx.navigateTo({
      url: '../goods/goodDetail',
    })
  },
  bindZtTime(e) {
    var zt = e.detail.value
    var flag = this.checkTime('zt', zt, false)
    if(flag == 0){ return }
  },
  bindTimeChange: function (e) {// tc时间设置
    var tc = e.detail.value
    var flag = this.checkTime('tc', tc, false)
    if (flag == 0) { return }
  },
  // 自提、同城时间校验
  checkTime: function (ty, time,iscre) {
    var flag = 1
    var dt = this.data.date
    var date = new Date()
    // 校验日期
    if (dt == '年/月/日') {
      wx.showModal({ title: '提示', content: '请选择日期！', showCancel: false })
      flag = 0
    } else {
      var ye = date.getFullYear(), mon = date.getMonth()+1, dy = date.getDate()
      if(mon < 10){mon = '0'+mon }
      if(dy < 10){dy = '0'+dy }
      var ymdInt = parseInt(dt.replace(/-/g, ''))// 当前
      var nnInt = parseInt(ye + '' + mon +'' + dy)
      if(ymdInt == nnInt){
        // 校验时间
        if (time != '') {
          var hr = date.getHours(), min = date.getMinutes()
          var sjStr = parseInt(time.replace(':', ''))
          var nnStr = parseInt(hr + '' + min)
          if (sjStr <= nnStr) {
            wx.showModal({ title: '提示', content: '选择时间应大于大于当前时间！', showCancel: false })
            flag = 0
          }
          if (!iscre) {
            if (ty == 'zt') {
              this.setData({ ztTime: time })
            } else {
              this.setData({ tcTime: time })
            }
          }

        } else {
          wx.showModal({ title: '提示', content: '请选择时间！', showCancel: false })
          flag = 0
        }
      }
    }
    return flag
  },
  bindContact: function (e) {
    var shop = this.data.shop
    var phone = shop.csPhone
    if(phone == null || phone == ''){
      wx.showModal({ title: '提示', content: '商家未提供电话！', showCancel: false })
      return
    }
    wx.makePhoneCall({
      phoneNumber: phone,
      success: function () {
        console.log('success_do')
      },
      fail: function () {
        console.log('fail_donot')
      }
    })
  },
  getBookArrInfo: function () {// 查询预定产品信息
    var that = this
    var header = { 'content-type': 'application/x-www-form-urlencoded' }
    var arr = that.data.bookArr
    var gids = ''
    for(var i = 0; i < arr.length; i++){
      if((i+1) == arr.length){
        gids += arr[i].goodsId
      }else{
        gids += arr[i].goodsId + ','
      }
    }
    var params = { shopId: app.shopId, googIds: gids }
    var encodingStr = app.ecbEncrypto(params)
    wx.request({
      url: app.url + '/cx/retail/getBookArrInfo.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr)
        if (rest.isSuccess == 0) {
          // 接收参数
          var shop = rest.shop
          var goodList = rest.goodList
          var mdList = rest.mdList
          var express = rest.express
          that.setData({ shop: shop, goodsList: goodList })
          var good = goodList[0]
          var st = good.sendType
          if (st == 'all'){
            // 处理门店
            if (mdList.length > 0) {
              var namearr = []
              var timearr = []
              var weekarr = []
              var idArr = []
              for (var i = 0; i < mdList.length; i++) {
                if (mdList[i].storeState) {
                  namearr.push(mdList[i].storeName)
                  timearr.push(mdList[i].hours)
                  weekarr.push(mdList[i].weeks)
                  idArr.push(mdList[i].id)
                }
              }
              var newArr = []  // 默认门店时间
              newArr = timearr[0].split('-')
              that.setData({
                mdTypeArr: namearr, ztStart: newArr[0], ztEnd: newArr[1], allTimeArr: timearr,
                weekArr: weekarr, week: weekarr[0], mdIds: idArr, mdId: idArr[0],
                mdName: namearr[0]
              })
            } else {
              that.setData({ sendTypeArr: ["快递发货", "同城配送"] })
            }
            // 处理快递
            var tp = that.data.finalPrice
            var extype = good.expressType
            var sp = 0
            if (extype == 'express') {// 运费模板
              if (JSON.stringify(express) == "{}") {
                sp = 0
              } else {
                sp = express.sendPrice
              }
            } else {
              sp = good.postage
            }
            tp = parseFloat(tp) + parseFloat(sp)
            that.setData({ sendPrice: sp, finalPrice: tp.toFixed(2), express: express })
          } else if (st == 'express' || st == 'tc'){
            // 处理快递
            var tp = that.data.finalPrice
            var extype = good.expressType
            var sp = 0
            if (extype == 'express') {// 运费模板
              if (JSON.stringify(express) == "{}") {
                sp = 0
              } else {
                sp = express.sendPrice
              }
            } else {
              sp = good.postage
            }
            tp = parseFloat(tp) + parseFloat(sp)
            that.setData({ sendPrice: sp, finalPrice: tp.toFixed(2), express: express, sendTypeArr: ["快递发货"] })
          } else if(st == 'md'){
            // 处理门店
            if (mdList.length > 0) {
              var namearr = []
              var timearr = []
              var weekarr = []
              var idArr = []
              for (var i = 0; i < mdList.length; i++) {
                if (mdList[i].storeState) {
                  namearr.push(mdList[i].storeName)
                  timearr.push(mdList[i].hours)
                  weekarr.push(mdList[i].weeks)
                  idArr.push(mdList[i].id)
                }
              }
              var newArr = []  // 默认门店时间
              newArr = timearr[0].split('-')
              that.setData({
                mdTypeArr: namearr, ztStart: newArr[0], ztEnd: newArr[1], allTimeArr: timearr,
                weekArr: weekarr, week: weekarr[0], mdIds: idArr, mdId: idArr[0],
                mdName: namearr[0], sendTypeArr: ["门店自提"]
              })
            } else {
              that.setData({ sendTypeArr: ["快递发货", "同城配送"] })
            }
          }
          that.setData({ sendType: st })
        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false
          })
        }
      }
    })
  },
  bindToCoupons: function () {
    var num = this.data.couponsNum
    if (num > 0) {
      var par = this.data.couponsParam
      var params = JSON.stringify(par)
      params = escape(params)
      wx.navigateTo({
        url: '../goods/goodCoupons?params=' + params,
      })
    }
  },
  // 查询可使用优惠券
  getCouponsNum() {
    var that = this
    var header = { 'content-type': 'application/x-www-form-urlencoded' }
    var arr = that.data.bookArr
    var params = {
      shopId: app.shopId, memberId: app.memberId, state: 0, totalPrice: that.data.goodTotalPrice, bookArr: arr
    }
    that.setData({ couponsParam: params})
    var encodingStr = app.ecbEncrypto(params)
    wx.request({
      url: app.url + '/cx/retail/getCouponsNum.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr)
        if (rest.isSuccess == 0) {
          var count = rest.total
          var info = ''
          if (parseInt(count) == 0){
            info = '暂无优惠券可用'
          }else{
            info = count + '张可用'
          }
          that.setData({ couponInfo: info, couponsNum: count })
        }
      }
    })
  },
  // 根据产品id查询价格
  findByGoodId: function (goodIds) {
    var arr = this.data.bookArr
    var price = 0
    for (var i = 0; i < arr.length; i++) {
      if (goodIds.indexOf(arr[i].goodsId+',') > 0){
        var ggArr = arr[i].ggArr
        for (var j = 0; j < ggArr.length; j++){
          price += parseFloat(ggArr[j].obj.price)
        }
      }
    }
    return price
  },
  creatOrder: function () {
    var that = this
    //校验库存&&下架&&生单
    var header = { 'content-type': 'application/x-www-form-urlencoded' }
    var params = {
      checkType: 3, bookArr: that.data.bookArr
    }
    var encodingStr = app.ecbEncrypto(params)
    wx.request({
      url: app.url + '/cx/retail/checkStock.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr)
        if (rest.isSuccess == 0) {
          // 生单接口
          var header = { 'content-type': 'application/x-www-form-urlencoded' }
          // 非空验证
          var pt = ''// 配送、自提时间
          var stp = that.data.sendType
          var st = that.data.st
          if (stp == 'express' || stp == 'tc' || (stp == 'all' && (st == 0 || st == 1))) {//快递
            if (that.data.sendAddress == '') {
              wx.showModal({ title: '提示', content: '请选择配送地址！', showCancel: false })
              return
            }
          }
          if (stp == 'md' || stp == 'tc' || (stp == 'all' && (st == 1 || st == 2))) {//自提
            if (that.data.date == '年/月/日') {
              wx.showModal({ title: '提示', content: '请选择日期！', showCancel: false })
              return
            }
            if (stp == 'md' || (stp == 'all' && st == 2)) {// 门店
              var zt = that.data.ztTime
              var flag = that.checkTime('zt', zt, true)
              if (flag == 0) { return }
            }
            if (stp == 'tc' || (stp == 'all' && st == 1)) {// 同城
              var tc = that.data.tcTime
              var flag = that.checkTime('tc', tc, true)
              if (flag == 0) { return }
            }
            pt = that.data.date + " " + (stp == 'md' ? that.data.ztTime : that.data.tcTime)
          }
          // 优惠券id
          var couId = 0
          var cou = that.data.coupon
          if (JSON.stringify(cou) == "{}") {
          } else {
            couId = cou.id
          }
          var ty = that.data.ty
          var nickName = '', avatarUrl = ''
          if (ty == "pp_pt"){
            var userInfo = app.userInfo
            nickName = userInfo.nickName
            avatarUrl = userInfo.avatarUrl
          }
          var info = {
            shopId: app.shopId, memberId: app.memberId, finalPrice: that.data.finalPrice,
            discountPrice: that.data.discountPrice, sendType: stp, st: st,
            sendPrice: that.data.sendPrice, sendName: that.data.sendName, sendPhone: that.data.sendPhone,
            sendAddress: that.data.sendAddress, message: that.data.message, pickTime: pt, storeId: that.data.mdId,
            storeName: that.data.mdName, mCouponId: couId, buyType: ty, nickName: nickName, avatarUrl: avatarUrl, 
            groupNo: that.data.gno, bookArr: that.data.bookArr
          }
          var params = { info: info }
          var encodingStr = app.ecbEncrypto(params)
          wx.showLoading({// 等待动画
            title: '订单正在提交中……',
          })
          
          wx.request({
            url: app.url + '/cx/retail/creatGoodOrder.htm',
            data: encodingStr,
            method: 'POST',
            header: header,
            success: function (res) {
              var decodingStr = app.ecbDecrypto(res.data)
              var rest = JSON.parse(decodingStr)
              if (rest.isSuccess == 0) {
                var orderId = rest.orderId
                // 清空购物车
                var haveGgArr = wx.getStorageSync("shopCarKey_" + app.shopId)// 缓存购物车
                wx.removeStorageSync("shopCarKey_" + app.shopId)
                var arr = []// 购买的集合
                var bookArr = that.data.bookArr
                for(var i = 0; i < bookArr.length; i++) {
                  var bggArr = bookArr[i].ggArr
                  if (bggArr.length > 0){
                    for (var j = 0; j < bggArr.length; j++) {
                      var ob = { buyNum: parseInt(bggArr[j].buyNum), goodsId: bookArr[i].goodsId, goodsName: bookArr[i].goodsName, goodsSmallImg: bookArr[i].goodsSmallImg, obj: bggArr[j].obj }
                      arr.push(ob)
                    }
                  }
                }
                for (var i = 0; i < haveGgArr.length; i++) {
                  for (var j = 0; j < arr.length; j++) {
                    if (JSON.stringify(haveGgArr[i]) == JSON.stringify(arr[j])){
                      haveGgArr.splice(i, 1)
                    }
                  }
                }
                wx.setStorageSync('shopCarKey_' + app.shopId, haveGgArr)
                if (rest.isPayZero){// 支付为0
                  wx.navigateTo({ url: '../orderDetail/orderDetail?orderNo=' + rest.orderNo })
                }else{
                  util.publicWechatPay(orderId) // 支付
                }
                
              } else {
                wx.showModal({
                  title: '提示',
                  content: rest.errorMsg,
                  showCancel: false,
                  success: function () {
                    if (rest.isSuccess == 5){
                      wx.navigateBack()
                    }
                  }
                })
              }
            },
            complete: function () {
              wx.hideLoading()
            }
          })
        } else {
          wx.hideLoading()
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false,
            success: function () {
              if (rest.isSuccess == 3) {// 下架，跳转到首页
                wx.switchTab({
                  url: '../index/index',
                })
              } else {
                wx.navigateBack()
              }
            }
          })
        }
      }
    })
    
  },
  optionWeeks: function (weeks) {
    var str = ''
    if (weeks.indexOf('周一') > 0){
      str += 1+','
    }
    if (weeks.indexOf('周二') > 0) {
      str += 2 + ','
    }
    if (weeks.indexOf('周三') > 0) {
      str += 3 + ','
    }
    if (weeks.indexOf('周四') > 0) {
      str += 4 + ','
    }
    if (weeks.indexOf('周五') > 0) {
      str += 5 + ','
    }
    if (weeks.indexOf('周六') > 0) {
      str += 6 + ','
    }
    if (weeks.indexOf('周日') > 0) {
      str += 7 + ','
    }
    return str
  }
})
